function varargout=mcaread(varargin)

% MCAREAD Read data in *.mca file generated by Surf(SPEC) at APS(9ID-C) or Ames Lab
% MCAREAD(FILE) returns the 2D data of VORTEX fluorescence scan.
% ******************************
% Input arguments: 
% 1st: MCA filename (string)
% 2nd: calibration coefficients for channels-> energy
%*******************************
% Output arguments:
% 1st: mac (2D data)
% 2nd: energy (vertical)
% 3rd: qz (horizontal)
% 4th: ct (counting time)
%
% Suggestion: imagesc(qz,energy,mac) to view the 2D color map of the data
% ******************************
% NOTE: The EDD detector at APS has 2048 channels.
% Wenjie Wang @ Ames Laboratory 
% version 1.0 (Aug-19-2014)
% ******************************

filename=varargin{1};
a=1;
b=0;
if nargin>1
    a=varargin{2}(1);
    b=varargin{2}(2);
end
nchan=2048;  % The total channel number of EDD
npline=25;   % The maximum number of values per line
channel=(1:1:nchan)';
energy=a*channel+b;
ct=[];  % detector live counting time (excluding detector dead time)
qz=[];  % Qz 
mca=[]; % Store the 2D data
[fid,message]=fopen(filename);
spec=zeros(size(channel)); % spectrum at each Qz
flag=0;
row=0;
% Each #S (scan) corresponds to one Qz and one spectrum (block of counts)
while feof(fid)==0
    strl=regexprep(fgetl(fid),'\',''); % STRL is the whole line/row read as a string
    line=strsplit(strtrim(strl),' '); % split the string (line) into fields (cell structure)
    if strcmp(line{1},'#Q')
        temp_qz=str2num(line{4});
        qz=[qz,temp_qz];
    end
    if strcmp(line{1},'#@CTIME')
        temp_ct=str2num(line{4});
        ct=[ct,temp_ct];
    end
    if flag==1 
        if isempty(strl) || np > nchan 
            flag=0;row=0;np=0;
            mca=[mca,spec]; % Finishing reading the whole block
        else
            for k=1:length(line)
                temp=str2num(line{k});
               % % % disp([temp_qz,row]) % for debugging 
                spec(np)=temp;
                np=np+1;
            end
            row=row+1; % Still in the same block (#S)
        end
    end
    
    if strcmp(line{1},'@A')
        np=1;
        for k=2:length(line)
            temp=str2num(line{k});
            spec(np)=temp;
            np=np+1;
            row=1;% the next row of the spectrum
        end
        flag=1; % Turn on the switch to read the rows of data
    end
    
end
fclose(fid);
varargout{1}=mca;
varargout{2}=energy;
varargout{3}=qz;
varargout{4}=ct;
return;